package com.mxx.bu_yang.activity.off_line;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.adapter.off_line.FileSelectorAdapter;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.DatePickDialog;
import com.mxx.bu_yang.utils.PermissionUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: Bu_Yang
 * @Package: com.mxx.bu_yang.activity
 * @ClassName: BarcodeListActivity
 * @Description: java类作用描述
 * @Author: 刘江飞
 * @Version: 1.0
 */
public class FileSelectNewActivity extends CommonTitleActivity implements OnItemChildClickListener {
    private RecyclerView rv_result;
    private FileSelectorAdapter selectorAdapter;
    private final Map<String, Object> map = new HashMap<>();
    private final int SCAN_CODE_OFF_IN = 5;
    private final int SCAN_CODE_OFF_OUT = 6;
    private final int SCAN_CODE_OFF_BACK = 7;
    private final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.READ_EXTERNAL_STORAGE
            , Manifest.permission.READ_CALENDAR
            , Manifest.permission.WRITE_CALENDAR
    };

    @Override

    public int getLayoutResId() {
        return R.layout.activity_file_selector;
    }

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_IMAGE;
    }

    @Override
    public void initView() {
        super.initView();
        rv_result = findViewById(R.id.rv_result);
        tv_title.setText("文件列表");
        iv_right.setImageResource(R.drawable.calendar);
        iv_right.setVisibility(View.GONE);
        initRvResult();
        initParams();
    }

    private void initRvResult() {
        LinearLayoutManager mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        rv_result.setLayoutManager(mManager);
        if (rv_result.getItemDecorationCount() == 0) {
            RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view
                        , @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    int mode = parent.getChildLayoutPosition(view);
                    if (mode == 0) {
                        outRect.top = 17;
                        outRect.bottom = 0;
                    } else if (mode == state.getItemCount() - 1) {
                        outRect.top = 0;
                        outRect.bottom = 17;
                    } else {
                        outRect.top = 0;
                        outRect.bottom = 0;
                    }
                }
            };
            rv_result.addItemDecoration(decoration);
        }

        selectorAdapter = new FileSelectorAdapter(R.layout.adapter_barcode_result);
        rv_result.setAdapter(selectorAdapter);
    }

    private void initParams() {
        int menu_id = (int) getSerValueByKey("menu_id");
        map.put("menu_id", menu_id);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkReadAndWritePermission();
    }

    private void checkReadAndWritePermission() {
        PermissionUtil
                .getInstance()
                .requestPermission(this, new PermissionUtil.IPermissionListener() {
                    @Override
                    public void allPermissionGranted() {
                        String path = getSDPath();
                        map.put("path", path);
                        List<String> list = loadFileByPath(path);
                        selectorAdapter.setList(list);
                    }

                    @Override
                    public void partPermissionRefuse() {
                        ToastUtils.showToast(FileSelectNewActivity.this, "权限被拒绝，请手动打开权限");
                    }
                }, permissions);
    }

    public String millionToFormatTime(long millions, String pattern) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        //前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
        Date dt = new Date(millions);
        return sdf.format(dt);  //得到精确到秒的表示
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().handlerActivityResult(requestCode, grantResults);
    }

    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = getExternalFilesDir("");
        }
        return sdDir != null ? sdDir.toString() : null;
    }


    private List<String> loadFileByPath(String path) {
        List<String> list = new ArrayList<>();
        if (path != null && !path.isEmpty()) {
            File file = new File(path);
            if (file.exists()) {
                String[] pathArray = file.list();
                list = getPaths(pathArray);
                if (path.equals(getSDPath())) {
                    List<String> regulationOrder = new ArrayList<>();
                    for (int menuId = 5; menuId < 8; menuId++) {
                        String dir_name = getDirNameByMenuId(menuId);
                        regulationOrder.add(dir_name);
                    }
                    Collections.sort(list, (o1, o2) -> {
                        int io1 = regulationOrder.indexOf(o1);
                        int io2 = regulationOrder.indexOf(o2);
                        return (io1 == -1 || io2 == -1) ? (io2 - io1) : (io1 - io2);
                    });
                } else {
                    Collections.sort(list, (o1, o2) -> o2.compareTo(o1));
                }
            }
        }
        return list;

    }

    private List<String> getPaths(String[] pathArray) {
        List<String> list = new ArrayList<>();
        if (pathArray == null || pathArray.length == 0) {
            return list;
        }
        Collections.addAll(list, pathArray);
        return list;
    }

    @Override
    public void initListener() {
        super.initListener();
        iv_right.setOnClickListener(this);
        selectorAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void titleRightImageClick() {
        super.titleRightImageClick();
        showDatePickerDialog();
    }

    private void showDatePickerDialog() {
        DatePickDialog mDatePicker = new DatePickDialog();
        mDatePicker.setOnSelectedDateListener((year, monthOfYear, dayOfMonth) -> {
            String time = year + "" + getMothOfYear(monthOfYear) + "" + getDayOfMonth(dayOfMonth);
            List<String> filterList = getFilterList(time);
            selectorAdapter.setList(filterList);
        });
        mDatePicker.show(getSupportFragmentManager(), "DatePickDialog");
    }

    private List<String> getFilterList(String time) {
        List<String> list = new ArrayList<>();
        if (time != null && !time.isEmpty()) {
            String path = (String) map.get("path");
            List<String> dataList = loadFileByPath(path);
            if (!dataList.isEmpty()) {
                for (String name : dataList) {
                    if (name.contains(time)) {
                        list.add(name);
                    }
                }
            }
        }
        return list;
    }

    private String getMothOfYear(int monthOfYear) {
        String s;
        if (monthOfYear > 0 && monthOfYear < 10) {
            s = "0" + monthOfYear;
        } else {
            s = monthOfYear + "";
        }
        return s;
    }

    private String getDayOfMonth(int dayOfMonth) {
        String s;
        if (dayOfMonth > 0 && dayOfMonth < 10) {
            s = "0" + dayOfMonth;
        } else {
            s = dayOfMonth + "";
        }
        return s;
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (view.getId() == R.id.tv_result) {
            String path = (String) map.get("path");
            String name = selectorAdapter.getItem(position);
            if (path.equals(getSDPath())) {
                iv_right.setVisibility(View.VISIBLE);
                path = getSDPath() + "/" + name;
                map.put("path", path);
                adapter.getData().clear();
                adapter.notifyDataSetChanged();
                Calendar calendar = Calendar.getInstance();
                String filter = millionToFormatTime(calendar.getTimeInMillis(), "yyyyMMdd");
                List<String> all_list = loadFileByPath(path);
                List<String> list = getFilterList(filter, all_list);
                selectorAdapter.setList(list);
            } else {
                int menu_id = (int) map.get("menu_id");
                backBarcodeList(menu_id, path + "/" + name);
            }
        }
    }

    private List<String> getFilterList(String filter, List<String> all_list) {
        List<String> list = new ArrayList<>();
        if (filter != null && !filter.isEmpty()
                && all_list != null && !all_list.isEmpty()) {
            for (String barcode : all_list) {
                if (barcode.contains(filter)) {
                    list.add(barcode);
                }
            }
        }
        return list;
    }

    private void backBarcodeList(int menu_id, String file_name) {
        if (menu_id != SCAN_CODE_OFF_IN && menu_id != SCAN_CODE_OFF_OUT && menu_id != SCAN_CODE_OFF_BACK) {
            return;
        }
        Intent mIntent = new Intent();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("menu_id", menu_id);
        mBundle.putSerializable("file_name", file_name);
        mIntent.putExtras(mBundle);
        setResult(0x1001, mIntent);
        finish();
    }

    private String getDirNameByMenuId(int menu_id) {
        if (menu_id != SCAN_CODE_OFF_IN && menu_id != SCAN_CODE_OFF_OUT && menu_id != SCAN_CODE_OFF_BACK) {
            return "";
        }
        String dir_path = "";
        if (menu_id == SCAN_CODE_OFF_IN) {
            dir_path = "离线入库";
        }
        if (menu_id == SCAN_CODE_OFF_OUT) {
            dir_path = "离线出库";
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            dir_path = "出库货品回退";
        }
        return dir_path;
    }

    @Override
    protected boolean isSave() {
        return true;
    }

    @Override
    public void onBackPressed() {
        backKeyPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void backKeyPressed() {
        String path = (String) map.get("path");
        if (!path.equals(getSDPath())) {
            iv_right.setVisibility(View.GONE);
            List<String> list = loadFileByPath(new File(path).getParent());
            selectorAdapter.setList(list);
            map.put("path", new File(path).getParent());
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void saveResult() {
        super.saveResult();
        backKeyPressed();
    }
}
